home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / ConfigParser.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  23KB  |  709 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Configuration file parser.
  5.  
  6. A setup file consists of sections, lead by a "[section]" header,
  7. and followed by "name: value" entries, with continuations and such in
  8. the style of RFC 822.
  9.  
  10. The option values can contain format strings which refer to other values in
  11. the same section, or values in a special [DEFAULT] section.
  12.  
  13. For example:
  14.  
  15.     something: %(dir)s/whatever
  16.  
  17. would resolve the "%(dir)s" to the value of dir.  All reference
  18. expansions are done late, on demand.
  19.  
  20. Intrinsic defaults can be specified by passing them into the
  21. ConfigParser constructor as a dictionary.
  22.  
  23. class:
  24.  
  25. ConfigParser -- responsible for parsing a list of
  26.                 configuration files, and managing the parsed database.
  27.  
  28.     methods:
  29.  
  30.     __init__(defaults=None)
  31.         create the parser and specify a dictionary of intrinsic defaults.  The
  32.         keys must be strings, the values must be appropriate for %()s string
  33.         interpolation.  Note that `__name__\' is always an intrinsic default;
  34.         its value is the section\'s name.
  35.  
  36.     sections()
  37.         return all the configuration section names, sans DEFAULT
  38.  
  39.     has_section(section)
  40.         return whether the given section exists
  41.  
  42.     has_option(section, option)
  43.         return whether the given option exists in the given section
  44.  
  45.     options(section)
  46.         return list of configuration options for the named section
  47.  
  48.     read(filenames)
  49.         read and parse the list of named configuration files, given by
  50.         name.  A single filename is also allowed.  Non-existing files
  51.         are ignored.  Return list of successfully read files.
  52.  
  53.     readfp(fp, filename=None)
  54.         read and parse one configuration file, given as a file object.
  55.         The filename defaults to fp.name; it is only used in error
  56.         messages (if fp has no `name\' attribute, the string `<???>\' is used).
  57.  
  58.     get(section, option, raw=False, vars=None)
  59.         return a string value for the named option.  All % interpolations are
  60.         expanded in the return values, based on the defaults passed into the
  61.         constructor and the DEFAULT section.  Additional substitutions may be
  62.         provided using the `vars\' argument, which must be a dictionary whose
  63.         contents override any pre-existing defaults.
  64.  
  65.     getint(section, options)
  66.         like get(), but convert value to an integer
  67.  
  68.     getfloat(section, options)
  69.         like get(), but convert value to a float
  70.  
  71.     getboolean(section, options)
  72.         like get(), but convert value to a boolean (currently case
  73.         insensitively defined as 0, false, no, off for False, and 1, true,
  74.         yes, on for True).  Returns False or True.
  75.  
  76.     items(section, raw=False, vars=None)
  77.         return a list of tuples with (name, value) for each option
  78.         in the section.
  79.  
  80.     remove_section(section)
  81.         remove the given file section and all its options
  82.  
  83.     remove_option(section, option)
  84.         remove the given option from the given section
  85.  
  86.     set(section, option, value)
  87.         set the given option
  88.  
  89.     write(fp)
  90.         write the configuration state in .ini format
  91. '''
  92. import re
  93. __all__ = [
  94.     'NoSectionError',
  95.     'DuplicateSectionError',
  96.     'NoOptionError',
  97.     'InterpolationError',
  98.     'InterpolationDepthError',
  99.     'InterpolationSyntaxError',
  100.     'ParsingError',
  101.     'MissingSectionHeaderError',
  102.     'ConfigParser',
  103.     'SafeConfigParser',
  104.     'RawConfigParser',
  105.     'DEFAULTSECT',
  106.     'MAX_INTERPOLATION_DEPTH']
  107. DEFAULTSECT = 'DEFAULT'
  108. MAX_INTERPOLATION_DEPTH = 10
  109.  
  110. class Error(Exception):
  111.     '''Base class for ConfigParser exceptions.'''
  112.     
  113.     def _get_message(self):
  114.         """Getter for 'message'; needed only to override deprecation in
  115.         BaseException."""
  116.         return self._Error__message
  117.  
  118.     
  119.     def _set_message(self, value):
  120.         """Setter for 'message'; needed only to override deprecation in
  121.         BaseException."""
  122.         self._Error__message = value
  123.  
  124.     message = property(_get_message, _set_message)
  125.     
  126.     def __init__(self, msg = ''):
  127.         self.message = msg
  128.         Exception.__init__(self, msg)
  129.  
  130.     
  131.     def __repr__(self):
  132.         return self.message
  133.  
  134.     __str__ = __repr__
  135.  
  136.  
  137. class NoSectionError(Error):
  138.     '''Raised when no section matches a requested option.'''
  139.     
  140.     def __init__(self, section):
  141.         Error.__init__(self, 'No section: %r' % (section,))
  142.         self.section = section
  143.  
  144.  
  145.  
  146. class DuplicateSectionError(Error):
  147.     '''Raised when a section is multiply-created.'''
  148.     
  149.     def __init__(self, section):
  150.         Error.__init__(self, 'Section %r already exists' % section)
  151.         self.section = section
  152.  
  153.  
  154.  
  155. class NoOptionError(Error):
  156.     '''A requested option was not found.'''
  157.     
  158.     def __init__(self, option, section):
  159.         Error.__init__(self, 'No option %r in section: %r' % (option, section))
  160.         self.option = option
  161.         self.section = section
  162.  
  163.  
  164.  
  165. class InterpolationError(Error):
  166.     '''Base class for interpolation-related exceptions.'''
  167.     
  168.     def __init__(self, option, section, msg):
  169.         Error.__init__(self, msg)
  170.         self.option = option
  171.         self.section = section
  172.  
  173.  
  174.  
  175. class InterpolationMissingOptionError(InterpolationError):
  176.     '''A string substitution required a setting which was not available.'''
  177.     
  178.     def __init__(self, option, section, rawval, reference):
  179.         msg = 'Bad value substitution:\n\tsection: [%s]\n\toption : %s\n\tkey    : %s\n\trawval : %s\n' % (section, option, reference, rawval)
  180.         InterpolationError.__init__(self, option, section, msg)
  181.         self.reference = reference
  182.  
  183.  
  184.  
  185. class InterpolationSyntaxError(InterpolationError):
  186.     '''Raised when the source text into which substitutions are made
  187.     does not conform to the required syntax.'''
  188.     pass
  189.  
  190.  
  191. class InterpolationDepthError(InterpolationError):
  192.     '''Raised when substitutions are nested too deeply.'''
  193.     
  194.     def __init__(self, option, section, rawval):
  195.         msg = 'Value interpolation too deeply recursive:\n\tsection: [%s]\n\toption : %s\n\trawval : %s\n' % (section, option, rawval)
  196.         InterpolationError.__init__(self, option, section, msg)
  197.  
  198.  
  199.  
  200. class ParsingError(Error):
  201.     '''Raised when a configuration file does not follow legal syntax.'''
  202.     
  203.     def __init__(self, filename):
  204.         Error.__init__(self, 'File contains parsing errors: %s' % filename)
  205.         self.filename = filename
  206.         self.errors = []
  207.  
  208.     
  209.     def append(self, lineno, line):
  210.         self.errors.append((lineno, line))
  211.         self.message += '\n\t[line %2d]: %s' % (lineno, line)
  212.  
  213.  
  214.  
  215. class MissingSectionHeaderError(ParsingError):
  216.     '''Raised when a key-value pair is found before any section header.'''
  217.     
  218.     def __init__(self, filename, lineno, line):
  219.         Error.__init__(self, 'File contains no section headers.\nfile: %s, line: %d\n%r' % (filename, lineno, line))
  220.         self.filename = filename
  221.         self.lineno = lineno
  222.         self.line = line
  223.  
  224.  
  225.  
  226. class RawConfigParser:
  227.     
  228.     def __init__(self, defaults = None, dict_type = dict):
  229.         self._dict = dict_type
  230.         self._sections = self._dict()
  231.         self._defaults = self._dict()
  232.         if defaults:
  233.             for key, value in defaults.items():
  234.                 self._defaults[self.optionxform(key)] = value
  235.             
  236.         
  237.  
  238.     
  239.     def defaults(self):
  240.         return self._defaults
  241.  
  242.     
  243.     def sections(self):
  244.         '''Return a list of section names, excluding [DEFAULT]'''
  245.         return self._sections.keys()
  246.  
  247.     
  248.     def add_section(self, section):
  249.         """Create a new section in the configuration.
  250.  
  251.         Raise DuplicateSectionError if a section by the specified name
  252.         already exists. Raise ValueError if name is DEFAULT or any of it's
  253.         case-insensitive variants.
  254.         """
  255.         if section.lower() == 'default':
  256.             raise ValueError, 'Invalid section name: %s' % section
  257.         section.lower() == 'default'
  258.         if section in self._sections:
  259.             raise DuplicateSectionError(section)
  260.         section in self._sections
  261.         self._sections[section] = self._dict()
  262.  
  263.     
  264.     def has_section(self, section):
  265.         '''Indicate whether the named section is present in the configuration.
  266.  
  267.         The DEFAULT section is not acknowledged.
  268.         '''
  269.         return section in self._sections
  270.  
  271.     
  272.     def options(self, section):
  273.         '''Return a list of option names for the given section name.'''
  274.         
  275.         try:
  276.             opts = self._sections[section].copy()
  277.         except KeyError:
  278.             raise NoSectionError(section)
  279.  
  280.         opts.update(self._defaults)
  281.         if '__name__' in opts:
  282.             del opts['__name__']
  283.         
  284.         return opts.keys()
  285.  
  286.     
  287.     def read(self, filenames):
  288.         """Read and parse a filename or a list of filenames.
  289.  
  290.         Files that cannot be opened are silently ignored; this is
  291.         designed so that you can specify a list of potential
  292.         configuration file locations (e.g. current directory, user's
  293.         home directory, systemwide directory), and all existing
  294.         configuration files in the list will be read.  A single
  295.         filename may also be given.
  296.  
  297.         Return list of successfully read files.
  298.         """
  299.         if isinstance(filenames, basestring):
  300.             filenames = [
  301.                 filenames]
  302.         
  303.         read_ok = []
  304.         for filename in filenames:
  305.             
  306.             try:
  307.                 fp = open(filename)
  308.             except IOError:
  309.                 continue
  310.  
  311.             self._read(fp, filename)
  312.             fp.close()
  313.             read_ok.append(filename)
  314.         
  315.         return read_ok
  316.  
  317.     
  318.     def readfp(self, fp, filename = None):
  319.         """Like read() but the argument must be a file-like object.
  320.  
  321.         The `fp' argument must have a `readline' method.  Optional
  322.         second argument is the `filename', which if not given, is
  323.         taken from fp.name.  If fp has no `name' attribute, `<???>' is
  324.         used.
  325.  
  326.         """
  327.         if filename is None:
  328.             
  329.             try:
  330.                 filename = fp.name
  331.             except AttributeError:
  332.                 filename = '<???>'
  333.             except:
  334.                 None<EXCEPTION MATCH>AttributeError
  335.             
  336.  
  337.         None<EXCEPTION MATCH>AttributeError
  338.         self._read(fp, filename)
  339.  
  340.     
  341.     def get(self, section, option):
  342.         opt = self.optionxform(option)
  343.         if section not in self._sections:
  344.             if section != DEFAULTSECT:
  345.                 raise NoSectionError(section)
  346.             section != DEFAULTSECT
  347.             if opt in self._defaults:
  348.                 return self._defaults[opt]
  349.             raise NoOptionError(option, section)
  350.         section not in self._sections
  351.         if opt in self._sections[section]:
  352.             return self._sections[section][opt]
  353.         if opt in self._defaults:
  354.             return self._defaults[opt]
  355.         raise NoOptionError(option, section)
  356.  
  357.     
  358.     def items(self, section):
  359.         
  360.         try:
  361.             d2 = self._sections[section]
  362.         except KeyError:
  363.             if section != DEFAULTSECT:
  364.                 raise NoSectionError(section)
  365.             section != DEFAULTSECT
  366.             d2 = self._dict()
  367.  
  368.         d = self._defaults.copy()
  369.         d.update(d2)
  370.         if '__name__' in d:
  371.             del d['__name__']
  372.         
  373.         return d.items()
  374.  
  375.     
  376.     def _get(self, section, conv, option):
  377.         return conv(self.get(section, option))
  378.  
  379.     
  380.     def getint(self, section, option):
  381.         return self._get(section, int, option)
  382.  
  383.     
  384.     def getfloat(self, section, option):
  385.         return self._get(section, float, option)
  386.  
  387.     _boolean_states = {
  388.         '1': True,
  389.         'yes': True,
  390.         'true': True,
  391.         'on': True,
  392.         '0': False,
  393.         'no': False,
  394.         'false': False,
  395.         'off': False }
  396.     
  397.     def getboolean(self, section, option):
  398.         v = self.get(section, option)
  399.         if v.lower() not in self._boolean_states:
  400.             raise ValueError, 'Not a boolean: %s' % v
  401.         v.lower() not in self._boolean_states
  402.         return self._boolean_states[v.lower()]
  403.  
  404.     
  405.     def optionxform(self, optionstr):
  406.         return optionstr.lower()
  407.  
  408.     
  409.     def has_option(self, section, option):
  410.         '''Check for the existence of a given option in a given section.'''
  411.         if not section or section == DEFAULTSECT:
  412.             option = self.optionxform(option)
  413.             return option in self._defaults
  414.         if section not in self._sections:
  415.             return False
  416.         option = self.optionxform(option)
  417.         if not option in self._sections[section]:
  418.             pass
  419.         return option in self._defaults
  420.  
  421.     
  422.     def set(self, section, option, value):
  423.         '''Set an option.'''
  424.         if not section or section == DEFAULTSECT:
  425.             sectdict = self._defaults
  426.         else:
  427.             
  428.             try:
  429.                 sectdict = self._sections[section]
  430.             except KeyError:
  431.                 raise NoSectionError(section)
  432.  
  433.         sectdict[self.optionxform(option)] = value
  434.  
  435.     
  436.     def write(self, fp):
  437.         '''Write an .ini-format representation of the configuration state.'''
  438.         if self._defaults:
  439.             fp.write('[%s]\n' % DEFAULTSECT)
  440.             for key, value in self._defaults.items():
  441.                 fp.write('%s = %s\n' % (key, str(value).replace('\n', '\n\t')))
  442.             
  443.             fp.write('\n')
  444.         
  445.         for section in self._sections:
  446.             fp.write('[%s]\n' % section)
  447.             for key, value in self._sections[section].items():
  448.                 if key != '__name__':
  449.                     fp.write('%s = %s\n' % (key, str(value).replace('\n', '\n\t')))
  450.                     continue
  451.             
  452.             fp.write('\n')
  453.         
  454.  
  455.     
  456.     def remove_option(self, section, option):
  457.         '''Remove an option.'''
  458.         if not section or section == DEFAULTSECT:
  459.             sectdict = self._defaults
  460.         else:
  461.             
  462.             try:
  463.                 sectdict = self._sections[section]
  464.             except KeyError:
  465.                 raise NoSectionError(section)
  466.  
  467.         option = self.optionxform(option)
  468.         existed = option in sectdict
  469.         if existed:
  470.             del sectdict[option]
  471.         
  472.         return existed
  473.  
  474.     
  475.     def remove_section(self, section):
  476.         '''Remove a file section.'''
  477.         existed = section in self._sections
  478.         if existed:
  479.             del self._sections[section]
  480.         
  481.         return existed
  482.  
  483.     SECTCRE = re.compile('\\[(?P<header>[^]]+)\\]')
  484.     OPTCRE = re.compile('(?P<option>[^:=\\s][^:=]*)\\s*(?P<vi>[:=])\\s*(?P<value>.*)$')
  485.     
  486.     def _read(self, fp, fpname):
  487.         """Parse a sectioned setup file.
  488.  
  489.         The sections in setup file contains a title line at the top,
  490.         indicated by a name in square brackets (`[]'), plus key/value
  491.         options lines, indicated by `name: value' format lines.
  492.         Continuations are represented by an embedded newline then
  493.         leading whitespace.  Blank lines, lines beginning with a '#',
  494.         and just about everything else are ignored.
  495.         """
  496.         cursect = None
  497.         optname = None
  498.         lineno = 0
  499.         e = None
  500.         while True:
  501.             line = fp.readline()
  502.             if not line:
  503.                 break
  504.             
  505.             lineno = lineno + 1
  506.             if line.strip() == '' or line[0] in '#;':
  507.                 continue
  508.             
  509.             if line.split(None, 1)[0].lower() == 'rem' and line[0] in 'rR':
  510.                 continue
  511.             
  512.             if line[0].isspace() and cursect is not None and optname:
  513.                 value = line.strip()
  514.                 if value:
  515.                     cursect[optname] = '%s\n%s' % (cursect[optname], value)
  516.                 
  517.             value
  518.             mo = self.SECTCRE.match(line)
  519.             if mo:
  520.                 sectname = mo.group('header')
  521.                 if sectname in self._sections:
  522.                     cursect = self._sections[sectname]
  523.                 elif sectname == DEFAULTSECT:
  524.                     cursect = self._defaults
  525.                 else:
  526.                     cursect = self._dict()
  527.                     cursect['__name__'] = sectname
  528.                     self._sections[sectname] = cursect
  529.                 optname = None
  530.                 continue
  531.             if cursect is None:
  532.                 raise MissingSectionHeaderError(fpname, lineno, line)
  533.             cursect is None
  534.             mo = self.OPTCRE.match(line)
  535.             if mo:
  536.                 (optname, vi, optval) = mo.group('option', 'vi', 'value')
  537.                 if vi in ('=', ':') and ';' in optval:
  538.                     pos = optval.find(';')
  539.                     if pos != -1 and optval[pos - 1].isspace():
  540.                         optval = optval[:pos]
  541.                     
  542.                 
  543.                 optval = optval.strip()
  544.                 if optval == '""':
  545.                     optval = ''
  546.                 
  547.                 optname = self.optionxform(optname.rstrip())
  548.                 cursect[optname] = optval
  549.                 continue
  550.             if not e:
  551.                 e = ParsingError(fpname)
  552.             
  553.             e.append(lineno, repr(line))
  554.         if e:
  555.             raise e
  556.         e
  557.  
  558.  
  559.  
  560. class ConfigParser(RawConfigParser):
  561.     
  562.     def get(self, section, option, raw = False, vars = None):
  563.         """Get an option value for a given section.
  564.  
  565.         All % interpolations are expanded in the return values, based on the
  566.         defaults passed into the constructor, unless the optional argument
  567.         `raw' is true.  Additional substitutions may be provided using the
  568.         `vars' argument, which must be a dictionary whose contents overrides
  569.         any pre-existing defaults.
  570.  
  571.         The section DEFAULT is special.
  572.         """
  573.         d = self._defaults.copy()
  574.         
  575.         try:
  576.             d.update(self._sections[section])
  577.         except KeyError:
  578.             if section != DEFAULTSECT:
  579.                 raise NoSectionError(section)
  580.             section != DEFAULTSECT
  581.  
  582.         if vars:
  583.             for key, value in vars.items():
  584.                 d[self.optionxform(key)] = value
  585.             
  586.         
  587.         option = self.optionxform(option)
  588.         
  589.         try:
  590.             value = d[option]
  591.         except KeyError:
  592.             raise NoOptionError(option, section)
  593.  
  594.         if raw:
  595.             return value
  596.         return self._interpolate(section, option, value, d)
  597.  
  598.     
  599.     def items(self, section, raw = False, vars = None):
  600.         """Return a list of tuples with (name, value) for each option
  601.         in the section.
  602.  
  603.         All % interpolations are expanded in the return values, based on the
  604.         defaults passed into the constructor, unless the optional argument
  605.         `raw' is true.  Additional substitutions may be provided using the
  606.         `vars' argument, which must be a dictionary whose contents overrides
  607.         any pre-existing defaults.
  608.  
  609.         The section DEFAULT is special.
  610.         """
  611.         d = self._defaults.copy()
  612.         
  613.         try:
  614.             d.update(self._sections[section])
  615.         except KeyError:
  616.             if section != DEFAULTSECT:
  617.                 raise NoSectionError(section)
  618.             section != DEFAULTSECT
  619.  
  620.         if vars:
  621.             for key, value in vars.items():
  622.                 d[self.optionxform(key)] = value
  623.             
  624.         
  625.         options = d.keys()
  626.         if '__name__' in options:
  627.             options.remove('__name__')
  628.         
  629.         if raw:
  630.             return [ (option, d[option]) for option in options ]
  631.         return [ (option, self._interpolate(section, option, d[option], d)) for option in options ]
  632.  
  633.     
  634.     def _interpolate(self, section, option, rawval, vars):
  635.         value = rawval
  636.         depth = MAX_INTERPOLATION_DEPTH
  637.         while depth:
  638.             depth -= 1
  639.             if '%(' in value:
  640.                 value = self._KEYCRE.sub(self._interpolation_replace, value)
  641.                 
  642.                 try:
  643.                     value = value % vars
  644.                 except KeyError:
  645.                     e = None
  646.                     raise InterpolationMissingOptionError(option, section, rawval, e.args[0])
  647.                 except:
  648.                     None<EXCEPTION MATCH>KeyError
  649.                 
  650.  
  651.             None<EXCEPTION MATCH>KeyError
  652.             break
  653.         if '%(' in value:
  654.             raise InterpolationDepthError(option, section, rawval)
  655.         '%(' in value
  656.         return value
  657.  
  658.     _KEYCRE = re.compile('%\\(([^)]*)\\)s|.')
  659.     
  660.     def _interpolation_replace(self, match):
  661.         s = match.group(1)
  662.         if s is None:
  663.             return match.group()
  664.         return '%%(%s)s' % self.optionxform(s)
  665.  
  666.  
  667.  
  668. class SafeConfigParser(ConfigParser):
  669.     
  670.     def _interpolate(self, section, option, rawval, vars):
  671.         L = []
  672.         self._interpolate_some(option, L, rawval, section, vars, 1)
  673.         return ''.join(L)
  674.  
  675.     _interpvar_re = re.compile('%\\(([^)]+)\\)s')
  676.     
  677.     def _interpolate_some(self, option, accum, rest, section, map, depth):
  678.         if depth > MAX_INTERPOLATION_DEPTH:
  679.             raise InterpolationDepthError(option, section, rest)
  680.         depth > MAX_INTERPOLATION_DEPTH
  681.         while rest:
  682.             p = rest.find('%')
  683.             if p < 0:
  684.                 accum.append(rest)
  685.                 return None
  686.             if p > 0:
  687.                 accum.append(rest[:p])
  688.                 rest = rest[p:]
  689.             
  690.             c = rest[1:2]
  691.             None if c == '%' else '%' in v
  692.             raise InterpolationSyntaxError(option, section, "'%%' must be followed by '%%' or '(', found: %r" % (rest,))
  693.  
  694.     
  695.     def set(self, section, option, value):
  696.         '''Set an option.  Extend ConfigParser.set: check for string values.'''
  697.         if not isinstance(value, basestring):
  698.             raise TypeError('option values must be strings')
  699.         isinstance(value, basestring)
  700.         tmp_value = value.replace('%%', '')
  701.         tmp_value = self._interpvar_re.sub('', tmp_value)
  702.         percent_index = tmp_value.find('%')
  703.         if percent_index != -1:
  704.             raise ValueError('invalid interpolation syntax in %r at position %d' % (value, percent_index))
  705.         percent_index != -1
  706.         ConfigParser.set(self, section, option, value)
  707.  
  708.  
  709.